<template>
  <NModal v-model:show="visible" title="授权权限" :mask-closable="false" transform-origin="center" preset="card" @after-leave="closeDrawer" class="w-1000px">
    <NScrollbar class="h-600px pr-20px">
      <NDataTable :columns="columns" :data="tableData" :single-line="false" striped />
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">取消</NButton>
        <NButton type="primary" @click="handleSubmit">提交</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<script setup lang="tsx">
import {reactive, toRefs, watch} from "vue";
import { NCheckbox } from 'naive-ui';

defineOptions({
  name: 'GrantPermissionModal'
});

interface Props {
  // 授权权限的角色ID
  rowData?: number;
}
interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const props = defineProps<Props>();

const visible = defineModel<boolean>('permissionVisible', {
  default: false
});

const state = reactive({
  tableData: [] as Api.SystemManage.GrantResource[],
})
// 转为ref后解构
const {tableData} = {...toRefs(state)};
// 监听打开窗口时，逻辑处理
watch(visible, () => {
  if (visible.value) {
    console.log("授权权限")
  }
})

// 提交
async function handleSubmit() {
  // request
  window.$message?.success('操作成功');
  // 取消、关闭弹框
  closeDrawer();
  // 调用父组件事件
  emit('submitted');
}

// 取消、关闭弹框
function closeDrawer() {
  visible.value = false;
}
const columns = [
  {
    key: 'parentName',
    title: '一级目录',
    align: 'center',
    width: 100,
    titleColSpan:1,
    rowSpan: (rowData:Api.SystemManage.GrantResource, rowIndex:number) => {
      return getLastIndex( rowIndex, [rowData.parentName], "parentName");
    },
    render: (row:Api.SystemManage.GrantResource)=> (
      <NCheckbox>
        {row.parentName}
      </NCheckbox>
    )
  },
  {
    key: 'title',
    title: '菜单',
    align: 'center',
    width: 100,
    render: (row:Api.SystemManage.GrantResource)=> (
      <NCheckbox>
        {row.title}
      </NCheckbox>
    )
  },
  {
    key: 'button',
    title: '按钮',
    align: 'center',
    width: 100,
    render: (row:Api.SystemManage.GrantResource) => (
      <div>
        {
          row.button !=null ? row.button.length > 0 &&
            row.button.map(item => (
              <NCheckbox>
                {item}
              </NCheckbox>
            )) : null
        }
      </div>
    ),
  }
]
// 定义一个函数，用于获取相同名称的最后一行的索引
const getLastIndex = (index: number, names: string[], type: string) => {
  const sameNameIndex = tableData.value.slice(index).findIndex((item) => {
    return names.some((name) => item["parentName"] !== name);
  });
  return sameNameIndex === -1 ? tableData.value.length  : sameNameIndex;
};
</script>

<style scoped>

</style>
